"""


"""
import time
from datetime import datetime, timedelta

from flask import current_app, jsonify
from flask import redirect
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News
from info.utils.response_code import RET
from . import admin_blu
from flask import render_template


@admin_blu.route("/login", methods=["POST", "GET"])
def login():
    if request.method == "GET":
        # 如果用户已经登录，  并且是 管理员， 跳转到后台index页面
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        if user_id and is_admin:
            return redirect("/admin/index")

        return render_template("admin/login.html")

    """
    1, 获取参数，判空
    2, 查询数据库，看是否有这个用户
    3, 校验密码是否正确
    4, 判断是否是管理员
    5, 登录成功，重定向到后台首页
    """

    # 1, 获取参数，判空
    data_dict = request.form
    username = data_dict.get("username")
    password = data_dict.get("password")
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不完整")
    # 2, 查询数据库，看是否有这个用户
    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据库查询失败")

    if not user:
        return render_template("admin/login.html", errmsg="用户不存在")
    # 3, 校验密码是否正确
    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="密码错误")
    # 4, 判断是否是管理员
    if not user.is_admin:
        return render_template("admin/login.html", errmsg="非管理员用户权限不足")

    # !!!!保持登录状态
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    session["is_admin"] = True

    # 5, 登录成功，重定向到后台首页
    # return redirect("/admin/index")
    return redirect(url_for('admin.index'))


@admin_blu.route("/index")
def index():

    return render_template("admin/index.html")


@admin_blu.route("/user_count")
def user_count():

    # 用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin != True).count()
    except Exception as e:
        current_app.logger.error(e)

    # 月新增数
    month_count = 0

    t = time.localtime()   # 获取系统时间对象
    # time.struct_time(tm_year=2019, tm_mon=2, tm_mday=28, tm_hour=15, tm_min=0, tm_sec=50, tm_wday=3, tm_yday=59,
    #                  tm_isdst=0)
    begin_mon_date_str = '%d-%02d-01' % (t.tm_year, t.tm_mon)
    # 字符串转时间对象，才能和User.create_time进行比较
    begin_mon_date = datetime.strptime(begin_mon_date_str, "%Y-%m-%d")
    try:
        # total_count = User.query.filter(User.is_admin != True, User.create_time > 本月01日00时00分00秒).count()
        month_count = User.query.filter(User.is_admin != True, User.create_time > begin_mon_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日新增数
    day_count = 0
    begin_day_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    begin_day_date = datetime.strptime(begin_day_date_str, "%Y-%m-%d")
    try:
        # day_count = User.query.filter(User.is_admin != True, User.create_time > 本日00时00分00秒).count()
        day_count = User.query.filter(User.is_admin != True, User.create_time > begin_day_date).count()
    except Exception as e:
        current_app.logger.error(e)


    # 折线图处理
    active_count = []   # 登陆数量
    active_time = []  # 时间
    begin_day_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    begin_day_date = datetime.strptime(begin_day_date_str, "%Y-%m-%d")   # 获取今日00时00分00秒的时间对象

    # 先查一天的登陆数量

    for i in range(0, 31):
        begin_date = begin_day_date - timedelta(days=i)   #　timedelta(days=i)　时间段
        end_date = begin_date + timedelta(days=1)
        try:
            # cot = User.query.filter(User.is_admin != True, 今天的00时<User.last_login<明天的00时).count()
            # cot = User.query.filter(User.is_admin != True, User.last_login>今天的00时, User.last_login<明天的00时).count()
            cot = User.query.filter(User.is_admin != True, User.last_login>begin_date, User.last_login<end_date).count()
        except Exception as e:
            current_app.logger.error(e)

        active_count.append(cot)
        active_time.append(begin_date.strftime("%Y-%m-%d"))  # 记得时间对象转换成字符串再返回前端

    active_time.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "month_count": month_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_time": active_time
    }

    return render_template("admin/user_count.html", data=data)


@admin_blu.route("/news_review")
def news_review():
    """返回待审核新闻列表"""
    keywords = request.args.get("keywords", None)

    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    news_list = []
    current_page = 1
    total_page = 1

    filters = [News.status != 0]

    if keywords:  # 如果用户有搜索关键字，则需要添加多这个查询条件
        filters.append(News.title.contains(keywords))

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    context = {"total_page": total_page, "current_page": current_page, "news_list": news_dict_list}

    return render_template('admin/news_review.html', data=context)


@admin_blu.route("/news_review_detail/<int:news_id>")
def news_review_detail(news_id):

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not news:
        return jsonify(errno=RET.NODATA,errmsg="没有这篇新闻")

    data = {
        "news": news.to_dict()
    }

    return render_template("admin/news_review_detail.html", data=data)


@admin_blu.route("/news_review_active", methods=["POST"])
def news_review_active():

    """

    # 1. 接受参数(两个参数  new_id, action的值如果是accept就通过，如果是reject就拒绝通过，拒绝的情况下再获取一个参数reason)
    # 2. 参数校验
    # 3、查询新闻是否存在
    # 4、判断action的值进行 执行对应操作(修改news.status 通过为0，不通过为-1)
    # 5、提交数据
    # 6、返回成功
    :return:
    """

    # 1. 接受参数(两个参数  new_id, action的值如果是accept就通过，如果是reject就拒绝通过，拒绝的情况下再获取一个参数reason)

    data_dict = request.json
    action = data_dict.get("action")
    news_id = data_dict.get("news_id")
    # 2. 参数校验
    if not all([action, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3、查询新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有这篇新闻")
    # 4、判断action的值进行 执行对应操作(修改news.status 通过为0，不通过为-1)
    if action == "accept":
        news.status = 0
    else:
        # 拒绝通过
        reason = data_dict.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR,errmsg="请输入拒绝原因")
        news.status = -1
        news.reason = reason
    # 5、提交数据
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="数据库操作错误")

    # 6、返回成功
    return jsonify(errno=RET.OK,errmsg="操作成功")